package com.billionsfinance.crs.common.websocket;

import com.alibaba.fastjson.JSON;
import com.billionsfinance.crs.common.CrsConstants;
import com.billionsfinance.crs.common.model.WebSocketMessageModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;

/**
 * @ FileName: HeartBeatCheckThread.java
 * @ Author: WeiHui-Z
 * @ Date: 2017-01-06  16:04
 * @ Version: v1.0.0
 */
public class HeartBeatCheckThread implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatCheckThread.class);

    @Override
    public void run() {
        try {
            Map<String, WebSocketSession> userSessions = TextMessageHandler.getUserSessions();
            for (WebSocketSession socketSession : userSessions.values()) {
                heartBeatCheck(socketSession);
            }
        } catch (Exception e) {
            LOGGER.error("心跳检测异常", e);
        }
    }

    /**
     * 心跳检测--保持连接存活
     *
     * @param session ws
     */
    private void heartBeatCheck(WebSocketSession session) throws IOException {
        WebSocketMessageModel message = new WebSocketMessageModel(CrsConstants.HEART_BEAT_CHECK);
        message.setData(System.currentTimeMillis());
        session.sendMessage(new TextMessage(JSON.toJSONString(message)));
    }
}
